import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Modal } from 'antd'
import './style'

class ActionModal extends Component {
  constructor (props) {
    super(props)

    this.state = {
      show: false,
      loading: false
    }

    this.sure = this.sure.bind(this)
    this.showModal = this.showModal.bind(this)
    this.hideModal = this.hideModal.bind(this)
    this.controlLoading = this.controlLoading.bind(this)
  }

  render () {
    const { loading } = this.state
    const { width, title } = this.props

    return (
      <Modal
        wrapClassName="action-modal"
        cancelText="取消"
        width={width}
        title={title}
        confirmLoading={loading}
        okText={loading ? 'saving...' : '保存'}
        okButtonProps={{
          className: 'successBtn',
          style: {width: '103px'}
        }}
        maskClosable={false}
        visible={this.state.show}
        onOk={this.sure}
        onCancel={this.hideModal}
      >
        {this.props.children}
      </Modal>
    )
  }

  sure () {
    this.props.okCallback()
  }

  showModal () {
    this.setState(() => ({
      show: true
    }))
  }

  hideModal () {
    this.setState(() => ({
      show: false
    }), () => {
      this.props.cancelCallback()
    })
  }

  controlLoading (show) {
    this.setState(() => ({
      loading: show
    }))
  }
}

ActionModal.propTypes = {
  width: PropTypes.string,
  title: PropTypes.string,
  okCallback: PropTypes.func,
  cancelCallback: PropTypes.func
}

ActionModal.defaultProps = {
  width: '520px',
  title: '',
  okCallback: () => {},
  cancelCallback: () => {}
}

export default ActionModal
